package dao

import (
	"context"
	"gorm.io/gorm"

	"password-verification-management-system/common"
	"password-verification-management-system/model"
)

type AdminDao struct {
	*gorm.DB
}

func RegisterAdmin(admin *model.Admin) {
	db := common.GetDB()
	db.Create(&admin)
}
func NewAdminDao(ctx context.Context) *AdminDao {
	return &AdminDao{common.GetDB()}
}

func NewAdminDaoByDB(db *gorm.DB) *AdminDao {
	return &AdminDao{db}
}

// CreateAdmin 创建管理员
func (dao *AdminDao) CreateAdmin(admin *model.Admin) (err error) {
	err = dao.DB.Model(&model.Admin{}).Create(&admin).Error
	return
}

// GetAdminEmailByName根据邮箱号获取管理员信息
func (dao *AdminDao) GetAdminEmailByName(username string) (admin *model.Admin, err error) {
	err = dao.DB.Model(&model.Admin{}).Where("username= ?", username).First(&admin).Error
	return
}

// ExistOrNotByAdminName 根据username判断是否存在该名字
func (dao *AdminDao) ExistOrNotByAdminName(username string) (admin *model.Admin, exist bool, err error) {
	var count int64
	err = dao.DB.Model(&model.Admin{}).Where("username=?", username).
		Count(&count).Error
	if count == 0 {
		return nil, false, err
	}
	err = dao.DB.Model(&model.Admin{}).Where("username=?", username).
		First(&admin).Error
	if err != nil {
		return nil, false, err
	}
	return admin, true, nil
}
